package com.mmlc.meimei.lichengkongjian.classify;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.httputil.EntryPageName;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.LogUtils;
import com.mmlc.businessutils.MyShareUtils;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.Adapter.RecycGridAdapter;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.been.Condition;
import com.mmlc.meimei.lichengkongjian.brand.ConditionFragment;
import com.mmlc.meimei.lichengkongjian.customview.LabelFlowLayout;
import com.mmlc.meimei.lichengkongjian.customview.SwipeRecyclerView;
import com.mmlc.network.filter.BannerRequestFilter;
import com.mmlc.network.filter.GoodsListRequestFilter;
import com.mmlc.network.responsebean.BannerResponseBean;
import com.mmlc.network.responsebean.CategoryListResponseBean;
import com.mmlc.network.responsebean.GoodsListResponseBean;
import com.mmlc.utils.AppUtils;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.ViewUtils;
import com.mmlc.widget.ViewBannerPager;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CategoryListActivity extends InterActivity implements ConditionFragment.OnDataChangeListener {

    @Override
    protected int initContentView() {
        return R.layout.activity_category_list;
    }

    String category;
    String categoryId, cate_id, relation_pos_id = "";

    @Override
    protected void initExtra() {
        super.initExtra();
        category = getIntent().getStringExtra("category");
        cate_id = categoryId = getIntent().getStringExtra("categoryId");
        relation_pos_id = getIntent().getStringExtra("relation_pos_id");

//        if (null != EntryPageName.globalRequestBean && null != EntryPageName.globalRequestBean.getData() && null != EntryPageName.globalRequestBean.getData().getPrice_section()) {
//            GlobalRequestBean.DataBean.PriceSectionBean price_section = EntryPageName.globalRequestBean.getData().getPrice_section();
//
//            section_min = minPrice = price_section.getMin();
//            section_max = maxPrice = price_section.getMax();
//            duration = section_max - section_min;
//        }
    }


    ViewBannerPager banner;

    TextView tv_title, tv_verify,
            tv_default, tv_new, tv_price, tv_filtrate;
    ImageView iv_price_filtrate;

    List<GoodsListResponseBean.DataBean.GoodslistBean> datas;


    DrawerLayout dl_condition;
    FrameLayout fr_label;
    LabelFlowLayout ll_labels;
    boolean isRefresh,isLoadMore,isFirst=true;
    SwipeRecyclerView mSwipeRecyclerView;
    RecycGridAdapter adapter;
    View nodataView;
    @Override
    protected void initView() {
        tv_title = ViewUtils.getView(this, R.id.tv_title);
        nodataView = ViewUtils.getView(this, R.id.nodataView);
        tv_verify = ViewUtils.getView(this, R.id.tv_verify);
        mSwipeRecyclerView = ViewUtils.getView(activity,R.id.swipeRecyclerView);
        banner = ViewUtils.getView(this, R.id.banner);
        dl_condition = ViewUtils.getView(this, R.id.dl_drawer);

        /** 导航栏 */

       tv_default = ViewUtils.getView(this, R.id.tv_default);
        tv_new = ViewUtils.getView(this, R.id.tv_new);
        tv_price = ViewUtils.getView(this, R.id.tv_price);
        tv_filtrate = ViewUtils.getView(this, R.id.tv_filtrate);

        iv_price_filtrate = ViewUtils.getView(activity, R.id.iv_price_filtrate);

        fr_label = ViewUtils.getView(this,R.id.fr_label);
        ll_labels = ViewUtils.getView(this,R.id.ll_labels);
        tv_title.setText(category);

        mSwipeRecyclerView.getSwipeRefreshLayout()
                .setColorSchemeColors(Color.RED);
        //set layoutManager
        GridLayoutManager manager = new GridLayoutManager(this,2);

        mSwipeRecyclerView.getRecyclerView().setLayoutManager(manager);
        datas = new ArrayList<>();
        adapter = new RecycGridAdapter(datas,this);
        mSwipeRecyclerView.setAdapter(adapter);
        mSwipeRecyclerView.setOnLoadListener(new SwipeRecyclerView.OnLoadListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                isLoadMore = false;
                pageNow = 0;
                initInfo();
            }

            @Override
            public void onLoadMore() {
                pageNow++;
                isLoadMore = true;
                isRefresh = false;
                initInfo();
            }
        });

        adapter.setmOnItemClickListener(new RecycGridAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(activity, ProductInfoActivity.class);
                intent.putExtra("name", datas.get(position).getGoods_name()).putExtra("goods_id", datas.get(position).getId());
                startActivity(intent);
            }
        });


        ConditionFragment fragment = new ConditionFragment();
        fragment.setArguments(getFragmentBundle());
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.fragment_container, fragment);
        ft.commit();
        fragment.setOnDataChangeListener(this);


    }

    private void addLabel() {
        fr_label.setVisibility(View.VISIBLE);
        if(ll_labels.getChildCount()>0){
            ll_labels.removeAllViews();
        }
        for(int i = 0; i < labels.size(); i ++){
            View view = LayoutInflater.from(this).inflate(R.layout.item_tag, ll_labels,false);
            TextView tv_tag = (TextView) view.findViewById(R.id.tv_tag);
            tv_tag.setText(labels.get(i));
            ll_labels.addView(view);
        }
    }

    private Bundle getFragmentBundle() {
        Bundle bundle = new Bundle();
        if (!TextUtils.isEmpty(cate_id)) {
            bundle.putString("categoeryId", cate_id);
            bundle.putString("categoeryName", category);
        }
        return bundle;
    }

    int filtrate = -1;

    ArrayList<CategoryListResponseBean.DataBean> cateDatas;

    int section_max, section_min;
    int duration = 100000;
    String minPrice, maxPrice;



    @Override
    protected void initEvent() {
        ViewUtils.getView(this, R.id.iv_back).setOnClickListener(this);
        ViewUtils.getView(this, R.id.tv_verify).setOnClickListener(this);
        ViewUtils.getView(this, R.id.tv_default).setOnClickListener(this);
        ViewUtils.getView(this, R.id.tv_new).setOnClickListener(this);
        ViewUtils.getView(this, R.id.tv_price).setOnClickListener(this);
        ViewUtils.getView(this, R.id.tv_filtrate).setOnClickListener(this);

    }

    int navFiltrate = 0;


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            //分享
            case R.id.tv_verify:
                showShare();
                break;
            case R.id.tv_default:

                if (navFiltrate != 0) {
                    resetFiltrate(0);
                }
                getCategoryList();
                break;
            case R.id.tv_new:

                if (navFiltrate != 1) {
                    resetFiltrate(1);
                }
                getCategoryList();
                break;
            case R.id.tv_price:

                if (navFiltrate == 2) {
                isUp=!isUp;
                }
                resetFiltrate(2);
                getCategoryList();
                break;
            case R.id.tv_filtrate:
            case R.id.tv_filtrate2:
                /** 筛选 根据结果展示：有选中：navFiltrate=3，resetFiltrate（3）,initInfo;未选中：filtrate不变化  */

                dl_condition.openDrawer(Gravity.RIGHT);
                break;
        }
    }


    UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            ToastUtils.showToast(share_media.toString());
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            ToastUtils.showToast(share_media.toString());
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            ToastUtils.showToast(share_media.toString());
        }
    };

    /**
     * 分享
     */
   /* UMSocialService mController;*/
    UMShareAPI mShareAPI = null;
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getApplicationContext(), "Authorize succeed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getApplicationContext(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };



    private void showShare() {

        getShareUrl();

    }


    private void getShareUrl() {
        StringBuffer str = null;
        if (null != EntryPageName.globalRequestBean && null != EntryPageName.globalRequestBean.getData() && null != EntryPageName.globalRequestBean.getData().getShare()
         &&null != EntryPageName.globalRequestBean.getData().getShare().getGoodslist()) {
            String baseUrl = EntryPageName.globalRequestBean.getData().getShare().getGoodslist();
            str = new StringBuffer(baseUrl);
        }


        if(filter!=null) {

            try {

                String keywords = URLEncoder.encode(filter.requestBean.keywords, "UTF-8");
                String season = URLEncoder.encode(filter.requestBean.season, "UTF-8");
                String name = URLEncoder.encode(tv_title.getText().toString(), "UTF-8");
                String secondname = URLEncoder.encode(name, "UTF-8");

                str.append("keywords="+keywords+"&"+
                        "cate_id="+filter.requestBean.cate_id+"&"+
                        "brand_id="+filter.requestBean.brand_id+"&"+
                        "is_new="+filter.requestBean.is_new+"&"+
                        "relation_pos_id="+relation_pos_id+"&"+
                        "min="+minPrice+"&"+
                        "max="+maxPrice+"&"+
                        "season="+season+"&"+
                        "years="+filter.requestBean.years+"&"+
                        "zg_flag="+filter.requestBean.zg_flag+"&"+
                        "sort="+filter.requestBean.sort+"&"+
                        "sort_type="+filter.requestBean.sort_type+"&"+
                        "pageNow="+filter.requestBean.pageNow+"&"+
                        "pageSize="+filter.requestBean.pageSize+"&"+
                        "name="+secondname
                        );

                MyShareUtils.showShare(tv_title.getText().toString(), "", new String(str),new String(str));
                LogUtils.e("fenxiangde url",new String(str));


            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);


    }
    private boolean isUp;



    /**
     * 重置导航状态
     */
    private void resetFiltrate(int navFiltrateId) {
        pageNow = 0;
        datas.clear();

        tv_default.setTextColor(getResources().getColor(R.color.text_grey));

        tv_new.setTextColor(getResources().getColor(R.color.text_grey));

        tv_price.setTextColor(getResources().getColor(R.color.text_grey));

        tv_filtrate.setTextColor(getResources().getColor(R.color.text_grey));

        iv_price_filtrate.setImageResource(R.drawable.price_grey);
        if (navFiltrateId == 0) {
            tv_default.setTextColor(getResources().getColor(R.color.text_black));

        } else if (navFiltrateId == 1) {
            tv_new.setTextColor(getResources().getColor(R.color.text_black));

        } else if (navFiltrateId == 2) {
            if (isUp)
            {
                iv_price_filtrate.setImageResource(R.drawable.price_up);
            }
            else{
                iv_price_filtrate.setImageResource(R.drawable.price_down);
            }

            tv_price.setTextColor(getResources().getColor(R.color.text_black));

        } else if (navFiltrateId == 3) {
            tv_filtrate.setTextColor(getResources().getColor(R.color.text_black));

        }
        navFiltrate = navFiltrateId;
    }



    int pageNow = 0;

    @Override
    protected void initInfo() {
        super.initInfo();

        getCategoryBanners();
        getCategoryList();

    }

    private void getCategoryBanners() {
        BannerRequestFilter filter = new BannerRequestFilter(activity);
        filter.requestBean.page = category != null && "力诚空间奥莱".equals(category) ? "best_lolever" : "goods_list";
        filter.requestBean.relation_pos_id = relation_pos_id;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BannerResponseBean>() {
            @Override
            public void onSuccess(BannerResponseBean result) {
                LogUtils.i(TAG, result.toString());
                if (result == null || result.getData() == null || result.getData().getBanner().getAd_list() == null ||
                        result.getData().getBanner().getAd_list().size() == 0) {
                    banner.setVisibility(View.GONE);
                    return;
                }
                banner.setDatas(result.getData().getBanner().getAd_list());

            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                LogUtils.e(TAG, serverError.toString());
            }
        });
    }

    List<String> labels;
    public GoodsListRequestFilter filter ;
    private void getCategoryList() {

        filter = new GoodsListRequestFilter(activity);
        filter.requestBean.cate_id = cate_id;
        filter.requestBean.pageNow = String.valueOf(pageNow);
        if(!TextUtils.isEmpty(minPrice)){
            filter.requestBean.price_section = minPrice;
        }
        if(!TextUtils.isEmpty(maxPrice)){
            filter.requestBean.price_section = maxPrice;
        }
        if(!TextUtils.isEmpty(minPrice) && !TextUtils.isEmpty(maxPrice)){
            filter.requestBean.price_section = minPrice + "," + maxPrice;
        }

        filter.requestBean.version = AppUtils.getVersionCode(this)+"";
        if (!TextUtils.isEmpty(keyword))
            filter.requestBean.keywords=keyword;
        if (!TextUtils.isEmpty(brandId))
            filter.requestBean.brand_id=brandId;
        if (!TextUtils.isEmpty(years))
            filter.requestBean.years=years;
        if (!TextUtils.isEmpty(season))
            filter.requestBean.season=season;
        if (navFiltrate == 0) {
            filter.requestBean.is_new = "0";
            filter.requestBean.sort = "";
        } else if (navFiltrate == 1) {
            filter.requestBean.is_new = "1";
            filter.requestBean.sort = "";
        } else if (navFiltrate == 2) {
            filter.requestBean.is_new = "0";
            filter.requestBean.sort = "price";
            if (isUp)
            {
                filter.requestBean.sort_type = "1";
            }
            else
                filter.requestBean.sort_type = "0";

        } else if (navFiltrate == 3) {
            if (filtrate != -1)
                filter.requestBean.cate_id = cateDatas.get(filtrate).getId();
            /**  价格区间 */
            filter.requestBean.is_new = "0";
            filter.requestBean.sort = "";
        }
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<GoodsListResponseBean>() {
            @Override
            public void onSuccess(GoodsListResponseBean result) {
                if(result!=null && result.getData()!=null && result.getData().getLabels()!=null
                        && result.getData().getLabels().size()>0){
                    labels = result.getData().getLabels();
                    addLabel();
                }else{
                    fr_label.setVisibility(View.GONE);
                }
                if(result==null) {
                    result = new GoodsListResponseBean();
                }
                if(pageNow==0){
                    if(result.getData().getGoodslist().size()==0){
                        nodataView.setVisibility(View.VISIBLE);
                        mSwipeRecyclerView.setVisibility(View.GONE);
                    }
                }
                if(isFirst){
                    datas.addAll(result.getData().getGoodslist());
                    adapter.notifyDataSetChanged();
                    isFirst = false;
                    if(result.getData().getGoodslist().size()<20){
                        mSwipeRecyclerView.setLoadMoreEnable(false);
                    }
                    return;
                }
                if(isLoadMore ) {
                    datas.addAll(result.getData().getGoodslist());
                    isLoadMore = false;
                    if(result.getData().getGoodslist().size()==0){
                        mSwipeRecyclerView.onNoMore("一  End  一");
                    }else{
                        mSwipeRecyclerView.stopLoadingMore();
                        adapter.notifyDataSetChanged();
                    }
                    adapter.notifyDataSetChanged();
                    return;
                }else if(isRefresh){
                    if(result.getData().getGoodslist().size()<20){
                        mSwipeRecyclerView.setLoadMoreEnable(false);
                    }
                    if(result.getData().getGoodslist().size() == 0){
                        mSwipeRecyclerView.complete();
                        isRefresh = false;
                        return;
                    }

                    datas.clear();
                    datas.addAll(result.getData().getGoodslist());
                    isRefresh = false;
                    mSwipeRecyclerView.complete();
                    adapter.notifyDataSetChanged();
                    return;
                }else {
                    datas.clear();
                    datas.addAll(result.getData().getGoodslist());
                    adapter.notifyDataSetChanged();
                    return;
                }

            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);

            }
        });

    }





    private String years;

    private String season;

    private String brandId;

    private String keyword="";

    @Override
    public void onChange(Condition condition) {
        if (TextUtils.equals(years, condition.getYearId())
                && TextUtils.equals(season, condition.getSeasonId())
                && TextUtils.equals(cate_id, condition.getCategoeryId())
                && TextUtils.equals(brandId, condition.getBrandId())
                && TextUtils.equals(minPrice, condition.getMin())
                && TextUtils.equals(maxPrice, condition.getMax())
                && TextUtils.equals(keyword,condition.getKeyword()))
            return;
        cate_id=condition.getCategoeryId();
        brandId=condition.getBrandId();
        season=condition.getSeasonId();
        years=condition.getYearId();
        keyword=condition.getKeyword();
        if (TextUtils.isEmpty(condition.getMin()))
        {
            minPrice="";
        }
        else
        {
            minPrice=condition.getMin();
        }
        if (TextUtils.isEmpty(condition.getMax()))
        {
            maxPrice="";
        }
        else
        {
            maxPrice=condition.getMax();
        }

        pageNow = 0;
        datas.clear();
        getCategoryList();


    }

    @Override
    public void close() {
        dl_condition.closeDrawer(Gravity.RIGHT);
    }
}
